package com.wpw.dream.excel.util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.util.CollectionUtils;

/**
 * 
 * 
 * 
 */
public class ExportExcelBuilder {

	private static Log log = LogFactory.getLog(ExportExcelBuilder.class);

	private static final String EXCEL_SUFFIEX1 = ".xls";
	private static final String EXCEL_SUFFIEX2 = ".xlsx";
	private static final String DEFAULT_SHEET = "sheet0";

	private static void setCommonAttr(String fileName, String sheetName, HttpServletResponse response) {
		if (StringUtils.isNotBlank(fileName)) {
			if (!fileName.endsWith(EXCEL_SUFFIEX1)
					&& !fileName.endsWith(EXCEL_SUFFIEX2)) {
				fileName += EXCEL_SUFFIEX1;
			}
		} else {
			fileName = System.currentTimeMillis() + EXCEL_SUFFIEX1;
		}

		if (StringUtils.isBlank(sheetName)) {
			sheetName = DEFAULT_SHEET;
		}
		
		 String file = fileName;
		try {
		    file = new String(fileName.getBytes("gb2312"), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            
        }
		response.setHeader("Content-Disposition", "attachment; filename="
				+ file);
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		//response.setCharacterEncoding("utf-8");
	}
	
	/**
	 * 
	 * @Description：
	 * @author: wupengwei
	 * @date: 2018年11月27日 下午4:40:19
	 * * @param fileName excel表名
	 * @param sheetName sheet名
	 * @param list 数据列表
	 * @param response
	 * @param widths
	 */
	public static <T> void buildCommonExcel(String fileName, String sheetName,
			List<T> list, Class<T> clazz, HttpServletResponse response, Integer[] widths) {
		setCommonAttr(fileName, sheetName, response);
		
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(sheetName);
		
		buildHead(sheet, clazz);
		for (int i = 0; i < widths.length; i++) {
			if (widths[i] != null) {
				sheet.setColumnWidth(i, widths[i] * 256);
			}
		}
		if (!CollectionUtils.isEmpty(list)) {
			buildData(sheet, list);
		}
		// writer
		ExportExcelUtils.write(response, sheet);
		
	}
	/**
	 * 导出基础excel 表
	 * 
	 * 需要 @Export 注明实体中需要导出excel中的属性
	 * 
	 * 例：@Export(titleName = "版本号")
	 * 
	 * @param <T>
	 * @param fileName excel表名
	 * @param sheetName sheet名
	 * @param list 数据列表
	 * @param response
	 */
	public static <T> void buildCommonExcel(String fileName, String sheetName,
			List<T> list, Class<T> clazz, HttpServletResponse response) {

		setCommonAttr(fileName, sheetName, response);

		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(sheetName);

		buildHead(sheet, clazz);
		if (!CollectionUtils.isEmpty(list)) {
			buildData(sheet, list);
		}
		// writer
		ExportExcelUtils.write(response, sheet);
	}

	private static <T> void buildHead(HSSFSheet sheet, Class<T> clazz) {
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell = null;
		Field[] fieldArray = clazz.getDeclaredFields();
		int titleIndex = 0;
		for (int i = 0; i < fieldArray.length; i++) {
			Field field = fieldArray[i];
			Export export = field.getAnnotation(Export.class);
			if (export != null) {
				cell = row.createCell(titleIndex++);
				cell.setCellValue(export.titleName());
			}
		}
	}

	private static <T> void buildData(HSSFSheet sheet, List<T> list) {
		// data
		HSSFRow row = null;
		int rowIndex = 1;
		for (T object : list) {
			if (object != null) {
				row = sheet.createRow(rowIndex++);
				Field[] fieldArray = object.getClass().getDeclaredFields();
				HSSFCell cell = null;
				int cellIndex = 0;
				for (int j = 0; j < fieldArray.length; j++) {

					Field field = fieldArray[j];
					field.setAccessible(true);
					Export export = field.getAnnotation(Export.class);
					if (export != null) {
						cell = row.createCell(cellIndex++);
						Object val = ExportExcelUtils.getFieldValue(object,
								field);
						cell.setCellValue(String.valueOf(val));
					}

				}
			}
		}
	}

}
